<template>
  <view class="tool-wrap">
    <view class="row">
      <input class="ipt" type="number" v-model.number="seconds" placeholder="秒数" placeholder-class="ph" />
      <button class="btn" @tap="toggle">{{ isRunning ? '暂停' : '开始' }}</button>
      <button class="btn" @tap="reset">重置</button>
    </view>
    <text class="clock">{{ display }}</text>
  </view>
</template>

<script>
export default {
  name: 'CountdownTimer',
  data() {
    return { seconds: 60, remaining: 60, timer: null, isRunning: false }
  },
  computed: {
    display() {
      const s = Math.max(0, this.remaining | 0)
      const mm = String(Math.floor(s / 60)).padStart(2, '0')
      const ss = String(s % 60).padStart(2, '0')
      return `${mm}:${ss}`
    }
  },
  methods: {
    toggle() {
      // 暂停
      if (this.isRunning) {
        if (this.timer) clearInterval(this.timer)
        this.timer = null
        this.isRunning = false
        uni.vibrateShort && uni.vibrateShort()
        uni.showToast({ title: '已暂停', icon: 'none' })
        return
      }

      // 开始或继续（不立即减一秒，第一秒到达时再变化）
      if (this.timer) clearInterval(this.timer)
      // 如果是初次开始且 remaining 未初始化，则同步为 seconds
      if (this.remaining == null) this.remaining = this.seconds
      this.isRunning = true
      uni.vibrateShort && uni.vibrateShort()
      uni.showToast({ title: '开始计时', icon: 'none' })
      this.timer = setInterval(() => {
        this.remaining--
        if (this.remaining <= 0) {
          clearInterval(this.timer)
          this.timer = null
          this.isRunning = false
          uni.vibrateShort && uni.vibrateShort()
          uni.showToast({ title: '时间到', icon: 'none' })
        }
      }, 1000)
    },
    reset() {
      if (this.timer) clearInterval(this.timer)
      this.timer = null
      this.isRunning = false
      this.remaining = this.seconds
    },
  },
  beforeDestroy() { if (this.timer) clearInterval(this.timer) }
}
</script>

<style>
.tool-wrap { display: grid; gap: 16rpx; }
.row { display: grid; grid-template-columns: 1fr 160rpx 160rpx; gap: 12rpx; }
.ipt { height: 64rpx; border-radius: 20rpx; padding: 0 20rpx; color: #e9ecff; background: rgba(255,255,255,.06); border: 2rpx solid rgba(255,255,255,.12); }
.ph { color: #a7b0d9; }
.btn { height: 60rpx; border-radius: 20rpx; border: 2rpx solid rgba(255,255,255,.12); background: rgba(255,255,255,.06); color: #e9ecff; font-size: 24rpx; }
.clock { text-align: center; font-weight: 700; font-size: 48rpx; letter-spacing: 2rpx; }
</style>


